import { GetUserFromSession, GetUserFromLocalStorage } from '~/plugins/Tools/utils/auth';
import { cons } from '~/plugins/Tools/utils/log';
import Config from '~/config';
let {Local} = Config;
const logout = `${Local.url}/login?userLogin=false`;
function routeFilter (route) {
  cons.l = color => {
    return `经过 routeFilter 过滤： 过滤URL: ${color.blue(route.path)}`;
  };
  if (route.path === '/') return true;
  let path = route.path.split('/');
  let appCode = path[1];
  if (!appCode || appCode !== Local.name) return true;
  if (path[2] === 'login') return true;
  cons.lH = color => {
    return `${color.green('新的请求')}  最终请求URL: ${color.blue(route.path)}`;
  };
  return false;
}

export default async ({ isServer, store, req, route, redirect }) => {
  if (routeFilter(route)) return;
  let path = route.path.split('/');
  let appCode = path[1];
  if (isServer && !req) return;
  const data = isServer ? await GetUserFromSession(req, redirect, route, appCode) : await GetUserFromLocalStorage(store, appCode);
  if (typeof data === 'undefined') {
    return;
  }
  try {
    if (data.auth) {
      if (path[2] === 'login') {
        cons.l = '已登录的用户跳转到主页面';
        cons.log();
        redirect('/' + appCode);
        return;
      }
      let step = '';
      for (let i = 2; i < path.length; i++) {
        if (typeof path[i] !== 'undefined') {
          step += path[i] + '_';
        }
      }
      if (step !== '' && data.auth.indexOf(step.substring(0, step.length - 1)) === -1) {
        throw new Error('没有对应页面权限！');
      }
      if (!store.state.USER.authUser) {
        cons.l = ('页面刷新重新赋值！');
        cons.log();
        store.commit('USER/SET', data);
      }
    } else if (store.state.USER.authUser) {
      cons.l = ('已登录的用户退出！');
      cons.log();
      store.commit('USER/DEL');
      if (path[2] === 'login') {
        return;
      }
      return isServer ? redirect(logout) : window.location.replace(logout);
    } else {
      cons.l = ('请求注销session 用户退出！');
      cons.log();
      if (path[2] === 'login') {
        return;
      }
      return isServer ? redirect(logout) : window.location.replace(logout);
    }
  } catch (err) {
    cons.lE = `data 为 ${data} err 为 ${err}`;
    store.commit('USER/DEL');
    if (path[2] === 'login') {
      return;
    }
    cons.log();
    return isServer ? redirect(logout) : window.location.replace(logout);
  }
};
